package pl.testowka.selenium;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;


public abstract class SeleniumBase {
	
	public WebDriver driver;
	public String baseUrl = "http://code.google.com";
	public StringBuffer verificationErrors = new StringBuffer();

	@Before
	public void setUp() throws Exception {
		driver = new FirefoxDriver();
		// driver = new HtmlUnitDriver();
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}
	
	@After
	public void tearDown() throws Exception {
		driver.quit();
		String verificationErrorString = verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			fail(verificationErrorString);
		}
	}

	public boolean isElementPresent(By by) {
		try {
			driver.findElement(by);
			return true;
		} catch (NoSuchElementException e) {
			return false;
		}
	}

	public void open(String path) {
		driver.get(baseUrl + path);
	}
	
	public void assertTextPresent(String text) {
		try {
			assertTrue(driver.getPageSource().contains(text)); }
		catch (Exception e) {
			verificationErrors.append(e.toString());
		} 
	}

	public void assertText(By identifier, String expected) {
		assertEquals(expected, driver.findElement(identifier).getText());
	}

	public void verifyText(By identifier, String expected) {
		try {
			assertEquals(expected, driver.findElement(identifier).getText());
		} catch (Error e) {
			verificationErrors.append(e.toString());
		}
	}

	public void insertText(By identifier, String text) {
		WebElement element = driver.findElement(identifier);
		
		element.clear();
		element.sendKeys(text);
	}
	
	public void click(By identifier) {
		driver.findElement(identifier).click();
	}


}